package com.yaj.myfactorysupport.config.security;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.yaj.myfactorysupport.util.ErrorCodeEnum;
import com.yaj.myfactorysupport.util.RespBean;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

/**
 * @ClassName RestAuthorizationEntryPoint
 * @Description 当未登录或者token失效时，自定义的返回结果
 * @date 2021/5/2 14:45
 * @Version 1.0
 */
@Component
public class RestAuthorizationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, AuthenticationException e) throws IOException, ServletException {
        httpServletResponse.setCharacterEncoding("UTF-8");
        httpServletResponse.setContentType("application/json");
        PrintWriter out = httpServletResponse.getWriter();
        RespBean respBean = RespBean.error(ErrorCodeEnum.登录过期重新登录.getCode(),ErrorCodeEnum.登录过期重新登录.getMsg());
        out.write(new ObjectMapper().writeValueAsString(respBean));
        out.flush();
        out.close();
    }
}
